/**
 ************************************************************************
  > File Name: models/index.js
  > Author: Leeiio <iio@iiobox.com>
  > Site: https://www.iiobox.com
  > Created Time: 06/04/17 20:32:13
 ************************************************************************/


var fs        = require('fs');
var path      = require('path');
var basename  = path.basename(__filename);
var Sequelize = require('sequelize');
var env       = process.env.NODE_ENV || 'development';
var config    = require('config-lite');

config.mysql.define = {
  charset: 'utf8mb4',
  collate: 'utf8mb4_unicode_ci'
};

if (process.env.DATABASE_URL) {
  var sequelize = new Sequelize(process.env.DATABASE_URL,config.mysql);
} else {
  var sequelize = new Sequelize(config.mysql.database, config.mysql.username, config.mysql.password, config.mysql);
}
var db        = {};

fs.readdirSync(__dirname).filter(function (file) {
  return file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js';
}).forEach(function (file) {
  var model = sequelize['import'](path.join(__dirname, file));
  db[model.name] = model;
});

Object.keys(db).forEach(function (modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
  db[modelName].pageOffset = function pageOffset(pageNum, limit) {
    if (isNaN(pageNum) || pageNum < 1) {
      pageNum = 1;
    }
    // return (pageNum - 1) * this.pageLimit();
    var _limit = limit || this.pageLimit();
    return (pageNum - 1) * _limit;
  };
  db[modelName].pageLimit =  function pageLimit(limit) {
    return limit || config.limit_per_page;
  };
  db[modelName].totalPages = function totalPages (totalNum, limit) {
    // var total = parseInt((totalNum + this.pageLimit() - 1) / this.pageLimit(), 10);
    // var arrayTotalPages = [];
    // for (var i = 1; i <= total; i++) {
    //   arrayTotalPages.push(i);
    // }
    // return arrayTotalPages;

    // return Math.ceil(totalNum / this.pageLimit());
    var _limit = limit || this.pageLimit();
    return Math.ceil(totalNum / _limit);
  };
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
